<?php
namespace app\admin\controller;

use app\common\model\DistributeUser;
use app\common\model\OrderOperate;
use app\common\model\OrderProduct;
use think\Db;
use think\Loader;
use think\Request;
use app\common\model\Product as ProductModel;
use app\common\model\Company as CompanyModel;
use app\admin\tool\Parser;
use app\common\model\Enroll as EnrollModel;
use app\common\model\Order as OrderModel;
use app\common\model\OrderProduct as OrderProductModel;
use app\common\model\OrderOperate as OrderOperateModel;
use app\common\model\Exhibition as ExhibitionModel;

/**
 * 采购订单的管理
 * Class OrderPurchase
 * @package app\admin\controller
 */
class OrderPurchase extends Base{

    /**
     * 订单列表
     * 采购只能查看自己的客户的订单 而且只能查看 相应的状态的订单
     * @param Request $request
     * @throws
     * @return \think\response\view
     */
    public function index(Request $request){
        $state = $request->get('state',1);
        $state_dict = get_order_state_purchase_dict();
        if(!in_array($state,$state_dict)){
            $this->error("参数错误");
        }

        $where = ['state'=>$state];

        //是否允许编辑
        $state_map =  get_order_state_purchase_map();
        $allow_edit_state_map = array_keys($state_map);
        $this-> data['allow_edit'] = false;
        if(in_array($state,$allow_edit_state_map)){
            $this-> data['allow_edit'] = true;
        }

        $user_id = $request->param('user_id');
        if(!$user_id){
            $this->error("请选择一个用户");
        }
        $distribute_user  = DistributeUser::where(['admin_id'=>$this->admin->id,'user_id'=>$user_id])->find();
        if(!$distribute_user){
            $this->error("该用户不存在 或者权限限制");
        }

        //只取了最近一次活动 不允许有两次活动同时举办
        $exhibition = ExhibitionModel::where('exhibition_time','>',time())->where('state',0)->order('exhibition_time desc')->find();
        $model = OrderModel::where('user_id',$user_id)->where('exhibition_id',$exhibition['id'])->where($where)->paginate(10);

        $this->data['title'] = '订单列表';
        $this->data['model'] = $model;
        $this->data['parser'] = new Parser();
        $this->data['column'] = $this->column();
        $this->data['state'] = $state;
        $this->data['state_dict'] = $state_dict;
        $this->data['user_id'] = $user_id;

        return view('',$this->data);
    }


    /**
     * 采购对订单进行状态的改变
     * @param Request $request
     * @throws
     * @return \think\response\view
     */
    public function edit(Request $request){
        $id = $request->param('id');
        $order = OrderModel::get($id);
        if(!$order){
            $this->error("非法操作");
        }

        $order->picture_list = json_decode($order->picture_list);
        $order_product = OrderProduct::where(['order_id'=>$order->id])->select();

        $this->data['model'] = $order;
        $this->data['order_product'] = $order_product;
        $this->data['title'] = '订单编辑';


        return view("",$this->data);
    }


    /**
     * 采购对订单的状态更新
     * @param Request $request
     * @throws
     */
    public function update(Request $request){
        $post = $request->post();

        $order_map = get_order_state_purchase_map();
        $order = OrderModel::get($post['id']);
        if(!$order){
            $this->error('订单不存在');
        }

        if(!in_array(intval($post['state']),$order_map[$order->state])){
            $this->error("错误的操作 ");
        }

        //如果是已经发货状态 检查物流公司和单号
        if($post['state'] == 3){
            if(!preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$post['delivery_company'])){
                $this->error("物流公司名称必须是中文");
            }
            if(!preg_match('/^[A-Za-z0-9]+$/',$post['delivery_num'])){
                $this->error("物流单号只允许字母和数字");
            }
        }

        Db::startTrans();
        try{
            $order->state = $post['state'];
            if($post['state'] == 3){
                $order->delivery_company = $post['delivery_company'];
                $order->delivery_num     = $post['delivery_num'];
            }
            $order->save();
            OrderOperate::log($this->admin->id,$order->id,$post['state'],$post['message']);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error("操作失败");
        }

        $this->success("操作成功",url('admin/order_purchase/index',array('user_id'=>$order['user_id'])));
    }


    public function column(){
        return [
            'order_num'=>['name'=>'订单编号','fun'=>'text','options'=>''],
            'total_price'=>['name'=>'总金额','fun'=>'text','options'=>''],
            'total_salary'=>['name'=>'总佣金','fun'=>'text','options'=>''],
            'cellphone' =>['name'=>'联系人手机','fun'=>'text','options'=>''],
            'add_time'=>['name'=>'添加时间','fun'=>'datetime','options'=>['format'=>'Y-m-d H:i']],
            'update_time'=>['name'=>'更新时间','fun'=>'text','options'=>[]],
        ];
    }
}